<template>
  <div class="app-container org">
    <el-card style="width: 100%">
      <!-- 搜索条件盒子 -->
      <p class="pinformation">搜索条件</p>
      <el-form :model="queryParams" ref="queryRef" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="模板编号：" prop="tableCode">
              <el-input v-model="queryParams.tableCode" placeholder="请输入模板编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="模板名称：" prop="tableName">
              <el-input v-model="queryParams.tableName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="模板类型：" prop="modelType">
              <el-select v-model="queryParams.modelType" placeholder="请选择模板类型" clearable>
                <el-option v-for="dict in sys_template_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="适用方案类型：" prop="appType" label-width="110">
              <el-select v-model="queryParams.appType" placeholder="请选择适用方案类型" clearable>
                <el-option v-for="dict in sys_contract_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="包含方法：" prop="methodName">
              <el-input v-model="queryParams.methodName" placeholder="请输入包含方法" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="success" icon="Search" @click="handleQuery">搜索</el-button>
              <div class="resetBtn" style="margin-left: 6px">
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row>
        <p class="pinformation" style="margin-top: 8.5px">
          原始记录公共模板列表
        </p>
        <p class="totalStyle" style="margin-right: 20px; margin-top: 6px">
          共 {{ total }} 条数据
        </p>
        <el-form-item label="模板类型：" prop="modelType">
          <el-select v-model="form.modelType" placeholder="选择模板类型" clearable>
            <el-option v-for="dict in sys_template_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-row style="padding-bottom: 14px; margin-left: 20px">
          <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
          <el-button style="color: red !important" link icon="delete" @click="handleDelete">批量删除</el-button>
          <!-- <el-button type="success" link icon="Plus" style="margin-left: 40px">批量导出空表</el-button> -->
        </el-row>
      </el-row>

      <el-table class="business" v-loading="loading" :data="tableTable" @selection-change="handleSelectionChange"
        ref="mainTableRef" row-key="tableId" default-expand-all>
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="模板类型" align="center" prop="modelTypeName" width="160" />
        <el-table-column label="模板名称" align="center" prop="tableName" :show-overflow-tooltip="true" />
        <el-table-column label="模板编号" align="center" prop="tableCode" width="160" />
        <el-table-column label="适用方案类型" align="center" prop="appTypeName" :show-overflow-tooltip="true" width="160">
          <template #default="scope">
            {{
              proxy.getItemByArrays(
                sys_contract_type,
                "value",
                scope.row.appType?.split(","),
                "label"
              )
            }}
          </template>
        </el-table-column>
        <el-table-column label="主续表" align="center" prop="tableMainName" width="80" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="创建人" align="center" prop="createUserName" width="90" />
        <el-table-column width="430" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-button link type="success">预览</el-button>
            <el-button link type="success">打印设置</el-button> -->
            <!-- <el-button link type="success">空表打印</el-button> -->
            <!-- <el-button link type="success">添加续表</el-button> -->
            <el-button link type="success" @click="editClick(scope.row)" v-if="!scope.row._tableId">编辑</el-button>
            <!-- <el-button link type="success" v-if="!scope.row._tabl  eId" @click="handleCopy(scope.row)">复制</el-button> -->
            <el-button link type="success" @click="handleDelete(scope.row)" v-if="!scope.row._tableId">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="open" :title="title" @close="closedDialog">
      <el-form label-width="95px" ref="subFileRef" :model="form" :rules="rules">
        <el-form-item label="模板名称：" prop="tableName">
          <el-input v-model="form.tableName" clearable placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板编号：" prop="tableCode">
          <el-input v-model="form.tableCode" clearable placeholder="请输入模板编号" />
        </el-form-item>
        <el-form-item label="适用类别：" prop="appTypes"
          v-if="form.modelType === 1 || form.modelType === 3 || form.modelType === 12">
          <el-select v-model="form.appTypes" placeholder="请选择适用适用类别" clearable v-if="form.tableMain === 0"
            style="width: 100%" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="4">
            <el-option v-for="dict in sys_contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主/续表：" prop="tableMain">
              <el-radio :label="0" v-model="form.tableMain">主表</el-radio>
              <el-radio :label="1" v-model="form.tableMain">续表</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-select v-model="form.aaa" placeholder="暂无" clearable style="width: 100%">
              <el-option label="暂无" value="" />
            </el-select>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="define">确 定</el-button>
          <el-button type="danger" @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Table">
import bus from "@/utils/eventBus";
import {
  listTable,
  delTable,
  addTable,
  tableCopy,
} from "@/api/templateEditor/table";
import useRouteView from "@/store/modules/routeView";
const router = useRouter();
const route = useRoute();

const routeViewStore = useRouteView();


const { proxy } = getCurrentInstance();
const { sys_template_type } = proxy.useShareDict(
  "sys_template_type"
);
const {
  sys_contract_type,
} = proxy.useOrgDict(
  "sys_contract_type",
);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const tableTable = ref([]);

// 弹窗字段
const title = ref("新增");
const open = ref(false);

const data = reactive({
  form: { tableMain: 0 },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    tableCode: [
      { required: true, message: "模板编辑不能为空", trigger: "blur" },
    ],
    tableName: [
      { required: true, message: "模板表名称不能为空", trigger: "blur" },
    ],
    appType: [{ required: true, message: "适用类别不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询模块列表 */
function getList() {
  loading.value = true;
  listTable(queryParams.value).then((response) => {
    tableTable.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {
    tableId: null,
    tableCode: null,
    tableName: null,
    tableType: null,
    appType: null,
    modelType: null,
    tableMain: null,
    parentId: null,
    isChild: null,
    tableVersion: null,
    createUserId: null,
    createTime: null,
    updateUserId: null,
    updateTime: null,
    delUserId: null,
    delTime: null,
    delFlag: null,
    remark: null,
  };
  proxy.resetForm("tableRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.pageNum = 1;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = [];
  selection.forEach((item) => {
    if (!item._tableId) {
      ids.value.push(item.tableId);
    }
  });
}

watch(
  () => route.path,
  (val) => {
    if (val == "/templateEditor/table") {
      getList();
    }
  }
);

/** 删除按钮操作 */
function handleDelete(row) {
  const _tableIds = row.tableId || ids.value;
  proxy.$modal
    .confirm('是否确认删除模块编号为"' + _tableIds + '"的数据项？')
    .then(function () {
      return delTable(_tableIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "template/table/export",
    {
      ...queryParams.value,
    },
    `table_${new Date().getTime()}.xlsx`
  );
}

function handleAdd() {
  if (!form.value.modelType) {
    proxy.$modal.msgError("请先选择要新增的模板类型");
    return false;
  }
  open.value = true;
}

function handleBathDel() { }

function define() {
  proxy.$refs["subFileRef"].validate((valid) => {
    if (valid) {
      if (form.value.tableMain === 1) {
        form.appTypes = [];
      }
      addTable(form.value).then((res) => {
        open.value = false;
        getList();
        if (routeViewStore.routeView) {
          proxy.$tab.closePage(routeViewStore.routeView);
        }
        if (form.value.modelType === 1 || form.value.modelType === 13) {
          router.push({
            path: "/templateEditor/template",
            query: { tableId: res.data },
          });

          return false;
        }
        if (form.value.modelType === 3) {
          router.push({
            path: "/templateEditor/labTemple",
            query: { tableId: res.data },
          });
          return false;
        }
        router.push({
          path: "/templateEditor/common",
          query: { tableId: res.data },
        });
      });
    }
  });
}

function handleCopy(row) {
  tableCopy(row.tableId).then((res) => {
    row.tableId = res.data;
    editClick(row);
  });
}

function closedDialog() {
  proxy.resetForm("subFileRef");
  // delete form.value.modelType;
}
function editClick(row) {
  if (routeViewStore.routeView) {
    proxy.$tab.closePage(routeViewStore.routeView);
  }
  if (row.modelType === 1 || row.modelType === 13) {
    router.push({
      path: "/templateEditor/template",
      query: { tableId: row.tableId },
    });
    return false;
  }
  debugger;
  if (row.modelType === 3 || row.modelType === 23) {
    router.push({
      path: "/templateEditor/labTemple",
      query: { tableId: row._tableId ? row._tableId : row.tableId },
    });
    return false;
  }
  router.push({
    path: "/templateEditor/common",
    query: { tableId: row.tableId },
  });
}

function selectable(row) {
  if (row._tableId) {
    return false;
  } else {
    return true;
  }
}

getList();

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
</script>
